package com.qianfeng.openapi.web.master.filter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.qianfeng.openapi.web.master.pojo.AdminUser;
import com.qianfeng.openapi.web.master.pojo.Menu;
import com.qianfeng.openapi.web.master.util.AdminConstants;
import com.qianfeng.openapi.web.master.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 登陆验证
 */
@WebFilter("/*")
public class SecurityFilter implements Filter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static String redirectUrl = "/login.html";

    private static final String[] freeUrlList = {"/index.html","/side","/logout"};

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    private static final String[] ignoreUrlList = {"/login.html", "/dologin", ".js", ".css", ".ico", ".jpg", ".png","/layui"};

    @Override
    public void destroy() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        // 获取用户请求时访问的路径
        String servletPath = request.getServletPath();
        if (null != request.getPathInfo()) {
            servletPath += request.getPathInfo();
        }

        // 针对哪些路径放行
        for (String str : ignoreUrlList) {
            if (servletPath.indexOf(str) != -1) {
                chain.doFilter(request, response);
                return;
            }
        }

        //1.1 获取请求中携带的cookie
        Cookie[] cookies = request.getCookies();
        //1.2 判断是否存在指定的cookie值
        String key = null;
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equalsIgnoreCase(AdminConstants.COOKIE_SESSION_USER_KEY)){
                    key = cookie.getValue();
                    break;
                }
            }
        }
        //1.3 从Redis中获取用户信息
        String adminUserJson = redisTemplate.opsForValue().get(AdminConstants.SESSION_USER + key);
        if(StringUtils.isEmpty(adminUserJson)){
            response.sendRedirect(request.getContextPath() + redirectUrl);
            return;
        }

        //1.4 将获取到的JSON字符串反序列化成对象
        AdminUser user = (AdminUser) JsonUtil.getObj(adminUserJson, AdminUser.class);

        if (user == null) {
            response.sendRedirect(request.getContextPath() + redirectUrl);
            return;
        }

        //1.5 活跃用户,重置生存时间
        redisTemplate.expire(AdminConstants.SESSION_USER + key,AdminConstants.SESSION_TIMEOUT, TimeUnit.SECONDS);

        for(String str:freeUrlList){
            if (servletPath.indexOf(str) != -1) {
                chain.doFilter(request, response);
                return;
            }
        }

        //1.1 从redis中获取用户的菜单信息
        String menuJson = redisTemplate.opsForValue().get(AdminConstants.USER_MENU + key);
        if(StringUtils.isEmpty(menuJson)){
            response.sendRedirect(request.getContextPath() + redirectUrl);
            return;
        }
        //1.2 反序列化为List集合
        List<Menu> menus = JsonUtil.getObj(menuJson, new TypeReference<List<Menu>>() {
        });
        //1.3 活跃用户,重置菜单的生存时间
        redisTemplate.expire(AdminConstants.USER_MENU + key,AdminConstants.SESSION_TIMEOUT, TimeUnit.SECONDS);

        Boolean hasPermission = false;

        // 判断用户是否拥有访问当前路径的权限
        for (Menu menu : menus) {
            if (!StringUtils.isEmpty(menu.getUrl()) && menu.getUrl().contains(servletPath)) {
                hasPermission = true;
                break;
            }
        }

        // 没有权限就进入到if中
        if (!hasPermission) {
            response.sendRedirect(request.getContextPath() + redirectUrl);
            return;
        }
        chain.doFilter(request, response);
    }


}
